<!--
 * @Author: ssh
 * @Email: shanshenghui@unisound.com
 * @Date: 2022-03-22 03:20:36
 * @LastEditors: ssh
 * @LastEditTime: 2025-09-24 10:21:33
-->
<template>
  <div>
    <h1>Socket.io 示例</h1>
    <div class="btn-box">
      <button @click="socketTestEmit">简单确认信息示例</button>
      <div>服务端返回数据：{{ socketTestBackData }}</div>
      <button @click="socketTest_Event">转发示例</button>
      <div>服务端返回数据：{{ socketTest_EventBackData }}</div>
      <button @click="socketTest_Broadcast">广播示例(请参考文章内容)</button>
      <div>服务端返回数据：{{ socketTest_BroadcastData }}</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, inject } from 'vue';
import { Socket } from 'socket.io-client';

const socket = inject('socket') as Socket;
const socketTestBackData = ref();
const socketTest_EventBackData = ref();
const socketTest_BroadcastData = ref();

const socketTestEmit = () => {
  socket.emit('socketTest', { test: '客户端发送的数据：简单确认信息示例' }, (data: any) => {
    console.log('socketTest', data);
    socketTestBackData.value =
      JSON.stringify(data) + ',' + new Date().toLocaleString();
  });
};

socket.on('socketTest2', (data) => {
  console.log('socketTest2', data);
  socketTest_EventBackData.value =
    JSON.stringify(data) + ',' + new Date().toLocaleString();
});

socket.on('socketTest3', (data) => {
  console.log('socketTest3', data);
  socketTest_BroadcastData.value =
    JSON.stringify(data) + ',' + new Date().toLocaleString();
});
const socketTest_Event = () => {
  socket.emit('socketTest_Event', { test: '转发示例' });
};

const socketTest_Broadcast = () => {
  socket.emit('socketTest_Broadcast', { test: '广播示例' });
};

onMounted(() => {
  socket.connect(); //连接socket服务器
});
</script>

<style>
.btn-box button {
  display: block;
  margin-top: 10px;
}
</style>
